package org.zfes.snowier.cloud.zbss.cms.words.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.zfes.snowier.core.data.DataSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.zfes.snowier.core.util.ZBeanUtil;
import org.zfes.snowier.core.util.ZDateUtil;
import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.common.dao.params.ParamMap;
import org.zfes.snowier.cloud.zbss.cms.words.service.ICmsWordsSensitiveService;
import org.zfes.snowier.cloud.zbss.cms.words.dao.CmsWordsSensitiveMapper;
import org.zfes.snowier.cloud.zbss.cms.words.model.CmsWordsSensitive;

import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class CmsWordsSensitiveServiceImpl implements ICmsWordsSensitiveService{
 	@Autowired
	private CmsWordsSensitiveMapper cmsWordsSensitiveMapper;
	
	@Transactional(rollbackFor=Exception.class)
 	@Override
	public void createCmsWordsSensitive(CmsWordsSensitive cmsWordsSensitive) {
		ZBeanUtil.setCreateInfo(cmsWordsSensitive);
		ZBeanUtil.validateBean(cmsWordsSensitive);
		cmsWordsSensitiveMapper.insertSelective(cmsWordsSensitive);
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<CmsWordsSensitive> loadCmsWordsSensitiveById(Long id) {
		if(id!=null){
			return Optional.ofNullable(cmsWordsSensitiveMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
		
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateCmsWordsSensitive(CmsWordsSensitive cmsWordsSensitive) {
		ZBeanUtil.validateBean(cmsWordsSensitive);
		cmsWordsSensitive.setUpdateTime(ZDateUtil.newDate());
		cmsWordsSensitiveMapper.updateByPrimaryKeySelective(cmsWordsSensitive);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteCmsWordsSensitive(Long id) {
		ZAssert.notNull(id, "请选择要操作的数据");
		cmsWordsSensitiveMapper.updateStatus(id, Byte.valueOf("-1"),ZDateUtil.newDate());
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void setCmsWordsSensitiveStatus(Long id, Byte status) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(status, "状态参数错误");
		if(!Stream.of(new Byte[] {-1,0,1}).anyMatch(val->val.equals(status))) {
			ZAlert.serviceLogicalError("状态参数错误");
		}
		cmsWordsSensitiveMapper.updateStatus( id,  status,ZDateUtil.newDate()) ;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadCmsWordsSensitiveDataSet(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		DataSet ds=DataSet.newDS2(cmsWordsSensitiveMapper.selectListCount(pm), cmsWordsSensitiveMapper.selectMapListPage(pm));
		return ds;
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	//后台：敏感词批量删除
	public void deleteCmsWordsSensitiveBatch(String idBatch) {
		ZAssert.notNull(idBatch, "请选择要操作的数据");
		List<Long> idList=Arrays.asList(idBatch.split(",")).stream().map(s->Long.parseLong(s.trim())).collect(Collectors.toList());
		for(int i=0;i<idList.size();i++) {
			cmsWordsSensitiveMapper.deleteByPrimaryKey(idList.get(i));
		}
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	//被调用：查看留言评论等文本中是否存在敏感词（返回首个敏感词）
	public List<String> isExistSensitive(String content) {
		//找出所有敏感词
		List<String> sensitiveWordsList=cmsWordsSensitiveMapper.loadSensitiveWords();
		char contentChar=' ';
		String sensitiveWords=null;
		String contentString=null;
		List<String> sensitiveList=new ArrayList<String>();
		for(int n=0;n<=content.length();n++) {
			contentChar=content.charAt(n);
			for(int i=0;i<=sensitiveWordsList.size();i++) {
				sensitiveWords=sensitiveWordsList.get(i);
				if(contentChar==sensitiveWords.charAt(0)) {//与敏感词的第一个字符对应
					int length=sensitiveWords.length();
					contentString=content.substring(n, n+length-2);//取出内容中敏感词长度的字符串
					if(contentString.equals(sensitiveWords)) {//找到敏感词
						sensitiveList.add(sensitiveWords);
						sensitiveList.add(i+"");//内容中敏感词起始位置
						sensitiveList.add(n+length-2+"");//内容中敏感词终止位置
						return sensitiveList;
					}
				}
			}
		}
		return null;
	}
	
	@Transactional(rollbackFor=Exception.class)
	//被调用：替换掉内容中的所有敏感词
	@Override
	public String replace(String content) {//找出敏感词，替换掉，知道找不出敏感词
		String newContent=content;//处理后的内容
		String waitDealContent=content;//未处理的内容
		int sensitiveEnd=0;
		List<String> sensitiveList=null;
		String sensitiveWord=null;
		String replaceWord=null;
		while(true){
			sensitiveList= isExistSensitive(waitDealContent);
			if(!sensitiveList.isEmpty()) {//有敏感词
			    sensitiveWord=sensitiveList.get(0);
			    sensitiveEnd=Integer.parseInt(sensitiveList.get(2));
				replaceWord=cmsWordsSensitiveMapper.selectReplaceWordByWords(sensitiveWord);
				newContent+=replaceWord;
				waitDealContent=waitDealContent.substring(sensitiveEnd+1);
			}
			else
				return newContent;
		}
	}
}